'use strict';

module.exports = ({ expiresIn, include }) => {
  return async (ctx, next) => {
    const { url, method } = ctx.request;
    const key = `${method.toLocaleUpperCase()} ${url}`;
    if (include.includes(key)) {
      const cache = await ctx.app.redis.get(key);
      if (cache) {
        ctx.body = {
          errorCode: 0,
          data: JSON.parse(cache),
        };
      } else {
        await next();
        await ctx.app.redis.set(key, JSON.stringify(ctx.response.body), 'EX', expiresIn);
      }
    } else {
      await next();
    }
  };
};
